/*
 * v1.1 by jetsum tonydon
 * netbeansIDE 7.1
 */
package cn.txdnet.txweb.utils;

import java.io.File;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import txdnet.util.FileUtil;
import txdnet.util.Logger;

/**
 *
 * @author txdnet
 */
public class VelocityUtil {
    
    public static String VM_EXT;
    
        
    public static void init(){
        try{
         Properties p = FileUtil.readPropertiesFile(VelocityUtil.class.getResourceAsStream("/velocity.properties")) ;
         String vm_path = p.getProperty("vm.path","/vm") ;
         VM_EXT = p.getProperty("vm.ext", ".vm");
         Velocity.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, WebUtil.WEB_APP_PATH.concat(vm_path));
         Velocity.setProperty(Velocity.RUNTIME_LOG, WebUtil.WEB_APP_PATH.concat( p.getProperty("velocity.log","/velocity.log") ));
         Velocity.init(p);
         Logger.debug(VelocityUtil.class,":: Velocity Init Properties. vm.path=".concat(vm_path));
        }catch(Exception ex){
            Logger.error(VelocityUtil.class, ex.toString());
        }
    }
    
    public static String mergeTemplateToString(String vm_file, Map m, String encoding){
        Writer w = new StringWriter();
        Velocity.mergeTemplate(vm_file, encoding, new VelocityContext(m), w);
        return w.toString();
    }
    
    public static boolean writeTemplateToFile(String vm_file, Map m, String encoding, String dist_file){
           boolean flag = true ;
        try{
            FileUtils.writeStringToFile(new File(dist_file), 
                    VelocityUtil.mergeTemplateToString(vm_file, m, encoding), encoding);
	}catch(Exception ex){
           Logger.error(VelocityUtil.class, ex.toString());
	   flag = false;
      }
          return flag ;
    }
}
